package upload

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/utils"
	"net/http"
	"path"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type UploadFileApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewUploadFileApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *UploadFileApiLogic {
	hostname, _ := os.Hostname()
	return &UploadFileApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *UploadFileApiLogic) UploadFileApi() (resp *types.UploadFileResp, err error) {
	// todo: add your logic here and delete this line
	_, file, err := l.Request.FormFile("file")
	fileType := path.Ext(file.Filename)
	if fileType == ".mp4" {
		if file.Size > 1024*1024*50 {
			return nil, errors.New("文件大小不能超过50M")
		}
	}

	if k.IsContains([]string{".jpg", ".gif", ".png", ".JPG", ".GIF", ".PNG"}, fileType) {
		if file.Size > 1024*1024*5 {
			return nil, errors.New("文件大小不能超过5M")
		}
	}
	fileName := file.Filename
	endpoint := l.svcCtx.Config.AliOssConfig.Endpoint
	accessKeyId := l.svcCtx.Config.AliOssConfig.AccessKeyID
	accessKeySecret := l.svcCtx.Config.AliOssConfig.AccessKeySecret
	bucketName := l.svcCtx.Config.AliOssConfig.BucketName
	bucketUrl := l.svcCtx.Config.AliOssConfig.BucketUrl
	fileOss := utils.NewRegisterOss(
		endpoint,
		accessKeyId,
		accessKeySecret,
		bucketName,
		bucketUrl,
		true,
		[]string{".jpg", ".gif", ".png", ".JPG", ".GIF", ".PNG", ".mp4"},
	)
	uploadFile, err := fileOss.UploadFile("static/upload", true, file.Size, file)
	return &types.UploadFileResp{
		Url:  uploadFile,
		Name: fileName,
	}, err
}
